#include <gtk/gtk.h>
#include <dlfcn.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <engine_if.h>

#ifndef HAS_MAIN
#include <main.h>
#endif

void engine_load(gchar* dllname, DockItemEngine* engine, DockItemEngineEventCallbacks* callbacks) {

  gchar* (*engine_get_name_function)();
  gchar* (*engine_get_description_function)();
  gchar* (*engine_get_author_function)();
  gchar* (*engine_get_version_function)();
  cairo_surface_t* (*engine_render_function)(DockItem*,cairo_t*);

  void* handle = dlopen(dllname, RTLD_NOW);
  if (handle == NULL) {
    g_print("udock plugin not found: %s: %s\n", dllname, dlerror());
    return;
  }

  dlerror();
  engine_render_function = dlsym(handle, "engine_item_render");
  g_print("render-funktion zugewiesen\n");
  engine_get_name_function = dlsym(handle, "engine_get_name");
  engine_get_description_function = dlsym(handle, "engine_get_description");
  engine_get_author_function = dlsym(handle, "engine_get_author");
  engine_get_version_function = dlsym(handle, "engine_get_version");

  engine->name = engine_get_name_function();
  g_print("%s\n", engine->name);
  engine->description = engine_get_description_function();
  engine->author = engine_get_author_function();
  engine->version = engine_get_version_function();
  engine->render = engine_render_function;

  engine->options = g_hash_table_new(g_direct_hash, g_direct_equal);

  callbacks->expose_callback = dlsym(handle, "on_item_expose");
  callbacks->redraw_callback = dlsym(handle, "on_item_redraw");
  callbacks->mouse_enter_callback = dlsym(handle, "on_item_mouse_enter");
  callbacks->mouse_move_callback = dlsym(handle, "on_item_mouse_move");
  callbacks->mouse_exit_callback = dlsym(handle, "on_item_mouse_exit");
  callbacks->mouse_down_callback = dlsym(handle, "on_item_mouse_down");
  callbacks->mouse_up_callback = dlsym(handle, "on_item_mouse_up");
  callbacks->mouse_scroll_up_callback = dlsym(handle, "on_item_mouse_scroll_up");
  callbacks->mouse_scroll_down_callback = dlsym(handle, "on_item_mouse_scroll_down");
  callbacks->mouse_rclick_callback = dlsym(handle, "on_item_mouse_rclick");
  callbacks->mouse_dnd_drop_callback = dlsym(handle, "on_item_mouse_dnd_drop_callback");

  callbacks->engine_init_callback = dlsym(handle, "engine_init");
}
